﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Caliburn.PresentationFramework.ApplicationModel;
using System.Disposables;
using System.Concurrency;
using System.Windows;
using Caliburn.PresentationFramework;

namespace PCUserTimer.ViewModels
{
    public abstract class ActivityViewModelBase : Presenter
    {
        protected readonly CompositeDisposable disposables = new CompositeDisposable();

        public ActivityViewModelBase(int minutes)
        {
            Popup = new EmptyPopup();

            disposables.Add(Observable.Interval(TimeSpan.FromSeconds(1)).Subscribe(_ => NotifyOfPropertyChange(() => Status)));

            EndsAt = TimeHelper.GetNextEvent(minutes);
        }

        public abstract string Status { get; }


        IDisposable endsAtTimer = Disposable.Empty;

        DateTimeOffset endsAt;
        public DateTimeOffset EndsAt
        {
            get { return endsAt; }
            set
            {
                endsAt = value;
                HasLapsed = false;

                endsAtTimer.Dispose();
                endsAtTimer = Observable.Timer(EndsAt, Scheduler.Dispatcher).Subscribe(_ => HasLapsed = true);
                disposables.Add(endsAtTimer);
            }
        }

        bool hasLapsed;
        public bool HasLapsed
        {
            get { return hasLapsed; }
            set
            {
                hasLapsed = value; NotifyOfPropertyChange(() => HasLapsed);

                Popup.Popup();

                if (HasLapsed && FinishWhenLapsed)
                    Finished.Raise(this);
            }
        }

        public virtual bool FinishWhenLapsed { get { return false; } }

        public virtual void ManuallyFinish()
        {
            Finished.Raise(this);
        }

        public event EventHandler Finished;

        public IPopup Popup { get; private set; }

        public override void ViewLoaded(object view, object context)
        {
            Popup = (IPopup)Window.GetWindow((DependencyObject)view);
        }

        protected override void OnShutdown()
        {
            disposables.Dispose();
            base.OnShutdown();
        }
    }
}
